extends Node

## 战斗管理器
## 负责管理战斗系统，包括随机遇敌、战斗场景切换等

signal battle_started
signal battle_ended(victory: bool)

var battle_scene_path: String = "res://battle/battle_scene.tscn"
var battle_5v5_scene_path: String = "res://battle/battle_5v5_scene.tscn"
var current_battle_scene = null
var battle_mode: String = "1v1"  # "1v1" 或 "5v5"
var previous_scene_path: String = ""
var is_in_battle: bool = false
var player_encounter_position: Vector2 = Vector2.ZERO  # 保存玩家遇怪时的位置
var player_encounter_direction: String = "down"  # 保存玩家遇怪时的方向

# 遇敌配置
var encounter_chance: float = 0.1  # 每步10%的遇敌概率
var steps_since_last_battle: int = 0
var min_steps_between_battles: int = 10  # 战斗间最少步数

func _ready():
	# 确保这个节点不会被自动释放
	process_mode = Node.PROCESS_MODE_ALWAYS

func get_current_scene_key() -> String:
	"""获取当前场景的key"""
	var current_scene = get_tree().current_scene
	if current_scene == null:
		return ""
	
	# 检查场景是否有scene_key属性
	if current_scene.has_method("get_scene_key"):
		return current_scene.get_scene_key()
	elif "scene_key" in current_scene:
		return current_scene.scene_key
	else:
		# 根据场景文件路径推断场景key
		var scene_path = current_scene.scene_file_path
		if scene_path.contains("scene2.tscn"):
			return "scene2"
		elif scene_path.contains("scene3.tscn"):
			return "scene3"
		elif scene_path.contains("scene1.tscn"):
			return "scene1"
		else:
			print("警告：无法识别场景key，场景路径: %s" % scene_path)
			return ""

func has_monsters_in_current_scene() -> bool:
	"""检查当前场景是否有配置的怪物"""
	if MonsterManager == null:
		print("警告：MonsterManager不可用，跳过遇敌检查")
		return false
	
	# 获取当前场景的key
	var current_scene_key = get_current_scene_key()
	if current_scene_key.is_empty():
		print("警告：无法获取当前场景key，跳过遇敌检查")
		return false
	
	# 检查该场景是否有配置的怪物
	var scene_monsters = MonsterManager.get_monsters_by_scene(current_scene_key)
	if scene_monsters.is_empty():
		print("场景 %s 中没有配置怪物，不会触发随机遇敌" % current_scene_key)
		return false
	
	print("场景 %s 中有 %d 种怪物可遇敌" % [current_scene_key, scene_monsters.size()])
	return true



func check_random_encounter() -> bool:
	"""检查是否触发随机遇敌"""
	if is_in_battle:
		return false
	
	steps_since_last_battle += 1
	
	# 如果距离上次战斗步数不够，不触发遇敌
	if steps_since_last_battle < min_steps_between_battles:
		return false
	
	# 检查当前场景是否有配置的怪物
	if not has_monsters_in_current_scene():
		return false
	
	# 随机判断是否遇敌
	if randf() < encounter_chance:
		start_random_battle()
		return true
	
	return false

func start_random_battle():
	"""开始随机战斗"""
	if is_in_battle:
		return
	
	# 记录当前场景
	previous_scene_path = get_tree().current_scene.scene_file_path
	
	# 保存玩家遇怪时的位置和方向
	if PlayerManager != null and PlayerManager.has_player():
		player_encounter_position = PlayerManager.get_player_position()
		var player = PlayerManager.get_current_player()
		if player != null:
			player_encounter_direction = player.get_direction_suffix()
		print("保存玩家遇怪位置: ", player_encounter_position)
		print("保存玩家遇怪方向: ", player_encounter_direction)
	
	# 检查是否有幻兽队伍，决定战斗模式
	var has_phantom_beasts = false
	if PhantomBeastManager != null:
		has_phantom_beasts = PhantomBeastManager.get_formation_size() > 0
	
	if has_phantom_beasts:
		# 5v5战斗模式
		battle_mode = "5v5"
		start_5v5_battle()
	else:
		# 传统1v1战斗模式
		battle_mode = "1v1"
		var enemy_data = get_random_enemy()
		start_battle(enemy_data)

func get_random_enemy() -> Dictionary:
	"""获取随机敌人数据（基于当前场景）"""
	if MonsterManager == null:
		print("错误：MonsterManager不可用")
		return {}
	
	# 获取当前场景的key
	var current_scene_key = get_current_scene_key()
	var enemy_data: Dictionary
	
	if current_scene_key.is_empty():
		print("警告：无法获取当前场景key，使用默认随机怪物")
		# 使用MonsterManager获取随机怪物（不限制场景）
		enemy_data = MonsterManager.get_random_monster_by_rarity_weight()
	else:
		# 使用MonsterManager获取指定场景的随机怪物
		enemy_data = MonsterManager.get_random_monster_by_scene(current_scene_key)
	
	if enemy_data.is_empty():
		print("错误：无法获取随机怪物数据")
		return {}
	
	return enemy_data

func start_5v5_battle():
	"""开始5v5战斗"""
	is_in_battle = true
	steps_since_last_battle = 0
	
	# 生成敌方队伍（5个怪物）
	var enemy_team = generate_enemy_team()
	if enemy_team.is_empty():
		print("错误：无法生成敌方队伍")
		return
	
	# 计算所有敌人的掉落物品
	current_battle_drops.clear()
	if MonsterManager != null:
		for enemy in enemy_team:
			if enemy.has("id"):
				var drops = MonsterManager.calculate_monster_drops(enemy["id"])
				current_battle_drops.append_array(drops)
	
	# 加载5v5战斗场景
	var battle_scene_resource = load(battle_5v5_scene_path)
	if battle_scene_resource == null:
		print("错误：无法加载5v5战斗场景")
		return
	
	# 创建战斗场景实例
	current_battle_scene = battle_scene_resource.instantiate()
	
	# 设置队伍数据
	add_child(current_battle_scene)
	
	# 获取玩家队伍数据（玩家+幻兽）
	var player_team = get_player_team_data()
	current_battle_scene.set_player_team_data(player_team)
	current_battle_scene.set_enemy_team_data(enemy_team)
	
	# 设置预计算的掉落物品
	if current_battle_scene.has_method("set_predetermined_drops"):
		current_battle_scene.set_predetermined_drops(current_battle_drops)
	
	# 连接战斗结束信号
	current_battle_scene.battle_ended.connect(_on_5v5_battle_ended)
	
	# 切换到战斗场景
	get_tree().current_scene.queue_free()
	get_tree().root.add_child(current_battle_scene)
	get_tree().current_scene = current_battle_scene
	
	battle_started.emit()
	print("5v5战斗开始！")

func generate_enemy_team() -> Array[Dictionary]:
	"""生成敌方队伍（根据玩家上阵幻兽数量动态调整，基于当前场景）"""
	var enemy_team: Array[Dictionary] = []
	
	if MonsterManager == null:
		print("错误：MonsterManager不可用")
		return enemy_team
	
	# 获取当前场景的key
	var current_scene_key = get_current_scene_key()
	
	# 获取玩家上阵的幻兽数量
	var player_formation_size = 0
	if PhantomBeastManager != null:
		player_formation_size = PhantomBeastManager.get_formation_size()
	
	# 计算敌人数量：上阵幻兽数量 + 1
	# 如果没有上阵幻兽，默认生成1个敌人
	var enemy_count = max(1, player_formation_size + 1)
	
	print("玩家上阵幻兽数量: %d，生成敌人数量: %d，当前场景: %s" % [player_formation_size, enemy_count, current_scene_key])
	
	# 生成对应数量的随机怪物
	for i in range(enemy_count):
		var enemy_data: Dictionary
		if current_scene_key.is_empty():
			# 如果无法获取场景key，使用默认方法
			enemy_data = MonsterManager.get_random_monster_by_rarity_weight()
		else:
			# 根据场景获取怪物
			enemy_data = MonsterManager.get_random_monster_by_scene(current_scene_key)
		
		if not enemy_data.is_empty():
			# 为每个怪物添加唯一标识
			enemy_data["battle_id"] = "enemy_%d" % i
			enemy_team.append(enemy_data)
		else:
			print("警告：无法获取第%d个怪物数据" % (i + 1))
	
	return enemy_team

func get_player_team_data() -> Array[Dictionary]:
	"""获取玩家队伍数据（玩家+幻兽）"""
	var player_team: Array[Dictionary] = []
	
	# 添加玩家数据
	var player_data = get_player_battle_data()
	player_data["battle_id"] = "player"
	player_data["is_player"] = true
	player_team.append(player_data)
	
	# 添加幻兽数据
	if PhantomBeastManager != null:
		var phantom_beasts = PhantomBeastManager.get_active_formation_data()
		for i in range(phantom_beasts.size()):
			var beast = phantom_beasts[i]
			# 转换幻兽数据为战斗数据格式
			var beast_battle_data = convert_phantom_beast_to_battle_data(beast)
			beast_battle_data["battle_id"] = "phantom_%d" % i
			beast_battle_data["is_phantom_beast"] = true
			player_team.append(beast_battle_data)
	
	return player_team

func convert_phantom_beast_to_battle_data(beast_data: Dictionary) -> Dictionary:
	"""将幻兽数据转换为战斗数据格式"""
	var stats = beast_data.get("stats", {})
	# 使用幻兽的实际当前血量，而不是最大血量
	var current_hp = stats.get("current_hp", stats.get("max_hp", 50))
	
	# 获取幻兽的显示名称（优先显示自定义昵称）
	var display_name = beast_data.get("name", "未知幻兽")
	var beast_id = beast_data.get("id", "")
	if PhantomBeastManager != null and beast_id != "":
		display_name = PhantomBeastManager.get_phantom_beast_display_name(beast_id)
	
	return {
		"name": display_name,
		"max_hp": stats.get("max_hp", 50),
		"current_hp": current_hp,
		"attack": stats.get("attack", 10),
		"defense": stats.get("defense", 5),
		"attack_speed": stats.get("attack_speed", 100),
		"level": beast_data.get("level", 1),
		"sprite_path": beast_data.get("sprite_path", ""),
		"id": beast_id
	}

func _on_5v5_battle_ended(victory: bool, final_player_hp: int, defeated_enemies_data: Array[Dictionary]):
	"""5v5战斗结束处理"""
	print("[DEBUG] _on_5v5_battle_ended 被调用，victory: ", victory)
	is_in_battle = false
	
	if victory:
		print("5v5战斗胜利！")
		
		# 先处理怪物掉落（包括金币）
		if MonsterManager != null:
			process_5v5_monster_drops(defeated_enemies_data)
		
		# 处理幻兽获得（尝试从每个敌人获得幻兽）
		if PhantomBeastManager != null:
			for enemy in defeated_enemies_data:
				if not enemy.is_empty():
					PhantomBeastManager.try_obtain_phantom_beast(enemy)
		
		# 最后处理经验值奖励（所有敌人的经验值总和）
		var total_exp = 0
		for enemy in defeated_enemies_data:
			total_exp += enemy.get("exp_reward", 0)
		
		if total_exp > 0:
			# 玩家和幻兽获得相同的经验值
			if PlayerStatsManager != null:
				PlayerStatsManager.gain_experience(total_exp)
				print("玩家获得经验值: ", total_exp)
			
			# 为所有参战的幻兽分配经验
			if PhantomBeastManager != null:
				var active_beasts = PhantomBeastManager.get_active_formation_ids()
				var active_beast_count = 0
				for beast_id in active_beasts:
					if beast_id != "":
						PhantomBeastManager.gain_phantom_beast_exp(beast_id, total_exp)
						active_beast_count += 1
				
				if active_beast_count > 0:
					print("上阵幻兽(%d只)获得经验值: %d" % [active_beast_count, total_exp])
		
		# 更新玩家生命值
		if PlayerStatsManager != null and final_player_hp >= 0:
			PlayerStatsManager.update_player_hp_after_battle(final_player_hp)
			print("战斗后玩家生命值: ", final_player_hp)
		
		# 返回之前的场景
		return_to_previous_scene()
	else:
		print("5v5战斗失败...")
		# 被击败时损失5%经验
		if PlayerStatsManager != null:
			PlayerStatsManager.lose_experience_on_defeat()
		# 回到场景1
		return_to_scene1()
	
	battle_ended.emit(victory)

func process_5v5_monster_drops(_defeated_enemies: Array[Dictionary]):
	"""处理5v5战斗的怪物掉落"""
	if ItemManager == null:
		print("错误：ItemManager不可用")
		return
	
	# 使用预先计算的掉落物品
	var drops = current_battle_drops
	if drops.is_empty():
		print("5v5战斗没有掉落任何物品")
		return
	
	print("\n=== 5v5战斗战利品掉落 ===")
	for drop in drops:
		var item_name = get_item_name(drop["type"], drop["id"])
		var quantity = drop["quantity"]
		
		if quantity > 1:
			print("获得: %s x%d" % [item_name, quantity])
		else:
			print("获得: %s" % item_name)
		
		# 将物品添加到玩家背包
		add_item_to_player_inventory(drop)
	
	print("========================")
	
	# 清空掉落缓存
	current_battle_drops.clear()

func start_battle(enemy_data: Dictionary):
	"""开始战斗"""
	is_in_battle = true
	steps_since_last_battle = 0
	
	# 预先计算掉落物品，确保显示和实际获得一致
	current_battle_drops.clear()
	if MonsterManager != null and enemy_data.has("id"):
		current_battle_drops = MonsterManager.calculate_monster_drops(enemy_data["id"])
	
	# 加载战斗场景
	var battle_scene_resource = load(battle_scene_path)
	if battle_scene_resource == null:
		print("错误：无法加载战斗场景")
		return
	
	# 创建战斗场景实例
	current_battle_scene = battle_scene_resource.instantiate()
	
	# 设置敌人数据
	add_child(current_battle_scene)
	current_battle_scene.set_enemy_data(enemy_data)
	
	# 设置玩家数据（从PlayerManager获取或使用默认值）
	var player_data = get_player_battle_data()
	current_battle_scene.set_player_data(player_data)
	
	# 将预计算的掉落物品传递给战斗场景
	if current_battle_scene.has_method("set_predetermined_drops"):
		current_battle_scene.set_predetermined_drops(current_battle_drops)
	
	# 连接战斗结束信号
	current_battle_scene.battle_ended.connect(_on_battle_ended)
	
	# 切换到战斗场景
	get_tree().current_scene.queue_free()
	get_tree().root.add_child(current_battle_scene)
	get_tree().current_scene = current_battle_scene
	
	battle_started.emit()
	print("战斗开始！遇到了 %s" % enemy_data.name)

func get_player_battle_data() -> Dictionary:
	"""获取玩家战斗数据"""
	if PlayerStatsManager != null:
		var player_data = PlayerStatsManager.get_player_battle_data()
		print("BattleManager获取玩家数据 - 生命值: %d/%d" % [player_data.current_hp, player_data.max_hp])
		return player_data
	else:
		# 备用默认数据
		return {
			"name": "勇者",
			"max_hp": 120,
			"current_hp": 120,
			"attack": 25,
			"defense": 12,
			"attack_speed": 100,
			"level": 1
		}

# 存储当前战斗的掉落物品，避免重复计算
var current_battle_drops: Array[Dictionary] = []

func _on_battle_ended(victory: bool, final_player_hp: int, defeated_enemy_data: Dictionary):
	"""战斗结束处理"""
	print("[DEBUG] _on_battle_ended 被调用，victory: ", victory)
	is_in_battle = false
	
	if victory:
		print("战斗胜利！")
		# 处理经验值奖励
		var exp_reward = 0
		if defeated_enemy_data.has("exp_reward"):
			exp_reward = defeated_enemy_data.exp_reward
		
		if exp_reward > 0:
			# 玩家获得经验
			if PlayerStatsManager != null:
				PlayerStatsManager.gain_experience(exp_reward)
				print("玩家获得经验值: ", exp_reward)
			
			# 为所有参战的幻兽分配经验
			if PhantomBeastManager != null:
				var active_beasts = PhantomBeastManager.get_active_formation_ids()
				var active_beast_count = 0
				for beast_id in active_beasts:
					if beast_id != "":
						PhantomBeastManager.gain_phantom_beast_exp(beast_id, exp_reward)
						active_beast_count += 1
				
				if active_beast_count > 0:
					print("上阵幻兽(%d只)获得经验值: %d" % [active_beast_count, exp_reward])
		
		# 处理幻兽获得
		if PhantomBeastManager != null and not defeated_enemy_data.is_empty():
			PhantomBeastManager.try_obtain_phantom_beast(defeated_enemy_data)
		
		# 处理怪物掉落
		if MonsterManager != null and defeated_enemy_data.has("id"):
			process_monster_drops(defeated_enemy_data["id"])
		
		# 更新玩家生命值（保留战斗后的生命值）
		if PlayerStatsManager != null and final_player_hp >= 0:
			PlayerStatsManager.update_player_hp_after_battle(final_player_hp)
			print("战斗后生命值: ", final_player_hp)
		# 返回之前的场景
		return_to_previous_scene()
	else:
		print("战斗失败...")
		# 被击败时损失5%经验
		if PlayerStatsManager != null:
			PlayerStatsManager.lose_experience_on_defeat()
		# 回到场景1
		return_to_scene1()
	
	battle_ended.emit(victory)

func return_to_previous_scene():
	"""返回之前的场景"""
	if previous_scene_path.is_empty():
		print("错误：没有记录之前的场景路径")
		return
	
	print("返回之前的场景: ", previous_scene_path)
	
	# 清理当前战斗场景
	if current_battle_scene != null:
		current_battle_scene.queue_free()
		current_battle_scene = null
	
	# 使用call_deferred确保在下一帧执行场景切换
	call_deferred("_change_scene_deferred", previous_scene_path)

func _change_scene_deferred(scene_path: String):
	"""延迟执行场景切换"""
	# 加载之前的场景
	var previous_scene_resource = load(scene_path)
	if previous_scene_resource == null:
		print("错误：无法加载之前的场景")
		return
	
	# 创建新场景实例
	var new_scene = previous_scene_resource.instantiate()
	if new_scene == null:
		print("错误：无法实例化场景")
		return
	
	# 获取当前场景树
	var tree = get_tree()
	var current_scene = tree.current_scene
	
	# 移除当前场景
	if current_scene != null:
		current_scene.free()
	
	# 添加新场景
	tree.root.add_child(new_scene)
	tree.current_scene = new_scene
	
	print("场景切换完成")
	
	# 等待一帧后重新生成玩家
	await tree.process_frame
	if PlayerManager != null and PlayerManager.has_method("spawn_player_in_current_scene"):
		# 如果有保存的遇怪位置，则在该位置生成玩家
		if player_encounter_position != Vector2.ZERO:
			# 临时保存方向信息到PlayerManager
			PlayerManager.player_data["direction"] = player_encounter_direction
			PlayerManager.spawn_player_in_current_scene(player_encounter_position)
			print("玩家在遇怪位置重新生成: ", player_encounter_position)
			print("恢复玩家方向: ", player_encounter_direction)
			# 清除保存的位置和方向
			player_encounter_position = Vector2.ZERO
			player_encounter_direction = "down"
		else:
			PlayerManager.spawn_player_in_current_scene()
			print("玩家重新生成完成")
	
	# 等待另一帧确保所有数据都已更新，然后触发自动保存
	await tree.process_frame
	if GameSaveManager != null and GameSaveManager.current_save_slot >= 0:
		print("场景切换完成后自动保存游戏...")
		GameSaveManager.save_game_to_slot(GameSaveManager.current_save_slot)
		GameSaveManager.reset_auto_save_timer()

func set_encounter_chance(chance: float):
	"""设置遇敌概率"""
	encounter_chance = clamp(chance, 0.0, 1.0)

func set_min_steps_between_battles(steps: int):
	"""设置战斗间最少步数"""
	min_steps_between_battles = max(0, steps)

func process_monster_drops(_monster_id: String):
	"""处理怪物掉落"""
	if ItemManager == null:
		print("错误：ItemManager不可用")
		return
	
	# 使用预先计算的掉落物品
	var drops = current_battle_drops
	if drops.is_empty():
		print("该怪物没有掉落任何物品")
		return
	
	print("\n=== 战利品掉落 ===")
	for drop in drops:
		var item_name = get_item_name(drop["type"], drop["id"])
		var quantity = drop["quantity"]
		
		if quantity > 1:
			print("获得: %s x%d" % [item_name, quantity])
		else:
			print("获得: %s" % item_name)
		
		# 将物品添加到玩家背包
		add_item_to_player_inventory(drop)
	
	print("==================")
	
	# 清空掉落缓存
	current_battle_drops.clear()

func get_item_name(item_type: String, item_id: String) -> String:
	"""获取物品名称"""
	match item_type:
		"gold":
			return "金币"
		"phantom_beast":
			if MonsterManager != null:
				var monster_data = MonsterManager.get_monster_by_id(item_id)
				if not monster_data.is_empty():
					return monster_data.get("name", item_id) + "幼崽"
			return item_id + "幼崽"
		"equipment":
			if ItemManager != null:
				var equipment_data = ItemManager.get_equipment_by_id(item_id)
				if equipment_data != null:
					return equipment_data.name
			return item_id
		"consumable":
			if ItemManager != null:
				var consumable_data = ItemManager.get_consumable_by_id(item_id)
				if consumable_data != null:
					return consumable_data.name
			return item_id
		"material":
			if ItemManager != null:
				var material_data = ItemManager.get_material_by_id(item_id)
				if material_data != null:
					return material_data.name
			return item_id
		_:
			return item_id

func add_item_to_player_inventory(drop: Dictionary):
	"""将掉落物品添加到玩家背包"""
	var item_type = drop["type"]
	var item_id = drop["id"]
	var quantity = drop["quantity"]
	
	# 特殊处理幻兽幼崽掉落
	if item_type == "phantom_beast":
		if PhantomBeastManager != null:
			# 根据怪物ID获取怪物数据
			var monster_data = MonsterManager.get_monster_by_id(item_id) if MonsterManager else {}
			if not monster_data.is_empty():
				# 直接获得幻兽（100%成功率，因为已经通过掉落检定）
				var phantom_success = PhantomBeastManager.try_obtain_phantom_beast(monster_data, true)
				if phantom_success:
					print("[幻兽系统] 成功获得幻兽幼崽: %s" % monster_data.get("name", item_id))
				else:
					print("[幻兽系统] 获得幻兽幼崽失败: %s" % monster_data.get("name", item_id))
			else:
				print("[幻兽系统] 错误：找不到怪物数据: %s" % item_id)
		else:
			print("[幻兽系统] 错误：PhantomBeastManager不可用")
		return
	
	# 特殊处理金币掉落
	if item_type == "gold":
		if PlayerStatsManager != null:
			PlayerStatsManager.add_gold(quantity)
			print("[金币系统] 获得金币: %d" % quantity)
		else:
			print("[金币系统] 错误：PlayerStatsManager不可用")
		return
	
	# 处理普通物品掉落
	if ItemManager == null:
		print("错误：ItemManager不可用")
		return
	
	# 根据物品类型获取ItemData对象
	var item_data = null
	match item_type:
		"equipment":
			item_data = ItemManager.get_equipment_by_id(item_id)
		"consumable":
			item_data = ItemManager.get_consumable_by_id(item_id)
		"material":
			item_data = ItemManager.get_material_by_id(item_id)
		_:
			print("未知物品类型: %s" % item_type)
			return
	
	if item_data == null:
		print("错误：找不到物品数据: %s" % item_id)
		return
	
	# 检查装备是否需要自动售卖
	if item_type == "equipment" and AutoSellManager != null:
		if AutoSellManager.should_auto_sell_item(item_data):
			# 自动售卖装备
			if AutoSellManager.auto_sell_item(item_data):
				return  # 已自动售卖，不添加到背包
	
	# 添加物品到背包
	var item_success = ItemManager.add_item_to_inventory(item_data, quantity)
	
	if item_success:
		print("[背包系统] 成功添加物品: %s %s x%d" % [item_type, item_id, quantity])
	else:
		print("[背包系统] 添加物品失败，背包可能已满: %s %s x%d" % [item_type, item_id, quantity])



func is_battle_active() -> bool:
	"""检查是否正在战斗中"""
	return is_in_battle

func return_to_scene1():
	"""被击败时回到场景1"""
	var scene1_path = "res://scene/scene1.tscn"
	
	print("[DEBUG] return_to_scene1 被调用")
	print("被击败，回到场景1: ", scene1_path)
	
	# 清理当前战斗场景
	if current_battle_scene != null:
		current_battle_scene.queue_free()
		current_battle_scene = null
	
	# 使用call_deferred确保在下一帧执行场景切换
	call_deferred("_change_scene_to_scene1_deferred", scene1_path)

func _change_scene_to_scene1_deferred(scene_path: String):
	"""延迟执行回到场景1的场景切换"""
	# 加载场景1
	var scene1_resource = load(scene_path)
	if scene1_resource == null:
		print("错误：无法加载场景1")
		return
	
	# 创建新场景实例
	var new_scene = scene1_resource.instantiate()
	if new_scene == null:
		print("错误：无法实例化场景1")
		return
	
	# 获取当前场景树
	var tree = get_tree()
	var current_scene = tree.current_scene
	
	# 移除当前场景
	if current_scene != null:
		current_scene.free()
	
	# 添加新场景
	tree.root.add_child(new_scene)
	tree.current_scene = new_scene
	
	print("场景切换到场景1完成")
	
	# 等待一帧后重新生成玩家在场景1的默认位置
	await tree.process_frame
	if PlayerManager != null and PlayerManager.has_method("spawn_player_in_current_scene"):
		# 死亡重生时，强制使用场景1的默认位置
		var scene1_default_position = Vector2(1088, 514)
		# 清除PlayerManager中可能错误的位置数据
		PlayerManager.player_data["position"] = Vector2.ZERO
		# 在指定位置生成玩家
		PlayerManager.spawn_player_at_position(scene1_default_position)
		print("玩家在场景1默认位置重新生成完成: ", scene1_default_position)
